
using System;
using System.Data;
using System.Linq;
using System.Linq.Dynamic;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;

using Abp.UI;
using Abp.AutoMapper;
using Abp.Extensions;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Application.Services.Dto;
using Abp.Linq.Extensions;


using Ixyu.Base.Configs;
using Ixyu.Base.Configs.Dtos;
using Newtonsoft.Json;


namespace Ixyu.Base.Configs
{
    /// <summary>
    /// AbpConfig应用层服务的接口实现方法  
    ///</summary>
    public class AbpConfigAppService : IxyuAppServiceBase
    {
        private readonly IRepository<AbpConfig, int> _entityRepository;


        /// <summary>
        /// 构造函数 
        ///</summary>
        public AbpConfigAppService(
        IRepository<AbpConfig, int> entityRepository
        
        )
        {
            _entityRepository = entityRepository; 
            
        }



		/// <summary>
		/// 通过指定id获取AbpConfigListDto信息
		/// </summary>
		 
		public async Task<T> GetByKey<T>(string key)
		{
			var entity = await _entityRepository.FirstOrDefaultAsync(u=>u.Key==key);
		    if (entity != null)
		    {
                return JsonConvert.DeserializeObject<T>(entity.Content);
		    }
		    return default(T);
		}

     
		public async Task CreateOrUpdate<T>(string key,string name,T content)
		{
		    var model = _entityRepository.FirstOrDefault(u => u.Key == key);
            var input=new AbpConfigInput();
		    input.Key = key;
		    input.Name = name;
		    input.Type = typeof(T).FullName;
		    input.Content = JsonConvert.SerializeObject(content);
			if (model!=null)
			{
			    input.Id = model.Id;
				await Update(input);
			}
			else
			{
				await Create(input);
			}
		}


		/// <summary>
		/// 新增AbpConfig
		/// </summary>
		
		protected virtual async Task<AbpConfigInput> Create(AbpConfigInput input)
		{
			//TODO:新增前的逻辑判断，是否允许新增

             var entity = new AbpConfig()
             {
                Key = input.Key,
                 Name =input.Name,
                 Content = input.Content,
                 Type = input.Type,
             };
			

			entity = await _entityRepository.InsertAsync(entity);
			return entity.MapTo<AbpConfigInput>();
		}

		/// <summary>
		/// 编辑AbpConfig
		/// </summary>
		
		protected virtual async Task Update(AbpConfigInput input)
		{
			//TODO:更新前的逻辑判断，是否允许更新

			var entity = await _entityRepository.GetAsync(input.Id);
		    entity.Content = input.Content;
		    entity.Type = input.Type;
            await _entityRepository.UpdateAsync(entity);
		}



		/// <summary>
		/// 删除AbpConfig信息的方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		
		public async Task Delete(EntityDto<int> input)
		{
			//TODO:删除前的逻辑判断，是否允许删除
			await _entityRepository.DeleteAsync(input.Id);
		}



    }
}


